package com.hitqz.robot.biz.flow.component.agv;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hitqz.robot.api.business.enums.RobotOtherCommandEnum;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotMapPos;
import com.hitqz.robot.api.common.entity.TicketsTask;
import com.hitqz.robot.biz.business.dispatch.DispatchService;
import com.hitqz.robot.biz.flow.config.FlowInterruptException;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.common.core.util.R;
import com.hitqz.robot.driver.model.IRobotPosDto;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2024/12/3
 */

@Slf4j
@LiteflowComponent(value = "GoTargetAndWaitForLifterDown", name = "[轮对/轮轴]前往放轮对")
@AllArgsConstructor
public class GoTargetAndWaitForLifterDown extends NodeComponent {

    private final RobotDriverService robotDriverService;

    private final RobotMapPosService robotMapPosService;

    private final RobotService robotService;

    private final DispatchService dispatchService;

    private static final int CMD_INVALID = -1;


    @Override
    public void process() throws Exception {
        LiteFlowUtil.checkInterruptFlag();
        IRobotPosDto iRobotPosDto = robotDriverService.getWebPos();
        FlowContextDto dto =  this.getRequestData();
        TicketsTask task = dto.getTicketsTask();
        log.info("任务数据 {}", task.getParseOrderParams());
        Robot robot = robotService.getDefaultRobot();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String targetPosName = Optional.ofNullable(ticketsDto.getModalData().get("targetPosName"))
                .orElse(ticketsDto.getModalData().get("targetPosCode")).toString();

        RobotMapPos robotMapPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                .eq(RobotMapPos::getName, targetPosName)
                .eq(RobotMapPos::getMapCode, robot.getMapCode()));
        if (robotMapPos == null) {
           robotMapPos = robotMapPosService.getOne(Wrappers.<RobotMapPos>lambdaQuery()
                    .eq(RobotMapPos::getCode, targetPosName)
                    .eq(RobotMapPos::getMapCode, robot.getMapCode()));
        }
        log.info("前往终端目标点{}", robotMapPos.getCode());
        boolean isSuccess = dispatchService.go2TargetPosition(robotMapPos, false);
        String varName = "rep_45_io_flag";
        String checkResult = "1";
        while (true) {
            try {
                iRobotPosDto = robotDriverService.getWebPos();
                LiteFlowUtil.checkInterruptFlag();
                if (iRobotPosDto == null || iRobotPosDto.getTaskStatus() == null) {
                    continue;
                }
                R result = robotDriverService.executeOtherCommand(RobotOtherCommandEnum.READ_VAR, "{\"varName\":\"" + varName + "\",\"checkResult\":\"" + checkResult + "\"}");
                String readResult = (String) result.getData();
                //log.info("放轮对读取的结果是: {}--{}", readResult, checkResult);
                if (checkResult.equals(readResult)) {
                    log.info("检测到前方有轮对");
                    break;
                }
                if (iRobotPosDto != null &&
                        iRobotPosDto.getCurrentStation() != null
                        && robotMapPos.getCode().equals(iRobotPosDto.getCurrentStation())
                        && iRobotPosDto.isReached()) {
                    log.info("机器人导航到达位置，可以放下轮对");
                    break;
                }
                TimeUnit.SECONDS.sleep(1);

            } catch (Exception e) {
                log.info("解析异常:" +e.getMessage());
                if (e instanceof FlowInterruptException) {
                    log.info("流程被中断");
                    break;
                }
            }
        }
    }
}
